package com.xncoding.pos.config.feign;

import com.xncoding.pos.common.MyConst;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * feign拦截器
 *
 * @Author guoyb
 * @Date 2022/6/8  18:58
 */
@Slf4j
public class FeignAuthRequestInterceptor implements RequestInterceptor {


    @Override
    public void apply(RequestTemplate requestTemplate) {
        log.info("feign拦截器-----打印日志------{}", requestTemplate.method());
        RequestAttributes requestAttributes1 = RequestContextHolder.getRequestAttributes();

        //必须配置,strategy: 'SEMAPHORE' #信号量隔离

        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        if (requestAttributes != null) {
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            String token = request.getHeader(MyConst.KEY_OAUTH2_TOKEN);
            requestTemplate.header(MyConst.KEY_OAUTH2_TOKEN, token);
        }


        // 这里可以添加feign请求的全局参数
        // ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // if (attributes == null || attributes.getRequest() == null) {
        //     return;
        // }
        // HttpServletRequest request = attributes.getRequest();
        // requestTemplate.header(MyConst.KEY_OAUTH2_TOKEN, request.getHeader(MyConst.KEY_OAUTH2_TOKEN));


        // //业务逻辑
        // requestTemplate.header("token", "1212");

    }


}